import { useState, useEffect, useCallback } from 'react'
import { User, LoginForm, LoginResponse } from '../types/index'
import { request } from '../services/api'

export const useAuth = () => {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(false)
  const [isAuthenticated, setIsAuthenticated] = useState(true) // 开发环境默认已认证

  // 初始化用户状态
  useEffect(() => {
    const token = localStorage.getItem('token')
    const userData = localStorage.getItem('user')
    
    if (token && userData) {
      try {
        const parsedUser = JSON.parse(userData)
        setUser(parsedUser)
        setIsAuthenticated(true)
      } catch (error) {
        console.error('解析用户数据失败:', error)
        localStorage.removeItem('token')
        localStorage.removeItem('user')
      }
    }
  }, [])

  // 登录
  const login = useCallback(async (loginForm: LoginForm): Promise<boolean> => {
    setLoading(true)
    try {
      const response = await request.post<LoginResponse>('/auth/login', loginForm)
      const { token, user: userData } = response.data
      
      // 保存认证信息
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(userData))
      
      setUser(userData)
      setIsAuthenticated(true)
      
      return true
    } catch (error) {
      console.error('登录失败:', error)
      return false
    } finally {
      setLoading(false)
    }
  }, [])

  // 登出
  const logout = useCallback(async () => {
    try {
      await request.post('/auth/logout')
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地数据
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      setUser(null)
      setIsAuthenticated(false)
    }
  }, [])

  // 获取当前用户信息
  const getCurrentUser = useCallback(async (): Promise<User | null> => {
    try {
      const response = await request.get<User>('/auth/current')
      const userData = response.data
      
      setUser(userData)
      localStorage.setItem('user', JSON.stringify(userData))
      
      return userData
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }, [])

  // 检查权限
  const hasPermission = useCallback((permission: string): boolean => {
    if (!user || !user.permissions) {
      return false
    }
    return user.permissions.includes(permission) || user.permissions.includes('*')
  }, [user])

  // 检查角色
  const hasRole = useCallback((role: string): boolean => {
    if (!user || !user.roles) {
      return false
    }
    return user.roles.includes(role) || user.roles.includes('admin')
  }, [user])

  return {
    user,
    loading,
    isAuthenticated,
    login,
    logout,
    getCurrentUser,
    hasPermission,
    hasRole,
  }
}